package com.feng.controller;

import com.feng.domain.ResponseResult;
import com.feng.domain.dto.LoginUserDto;
import com.feng.domain.entity.LoginUser;
import com.feng.domain.entity.User;
import com.feng.domain.vo.AdminUserInfoVo;
import com.feng.domain.vo.MenuVo;
import com.feng.domain.vo.RoutersVo;
import com.feng.domain.vo.UserInfoVo;
import com.feng.enums.AppHttpCodeEnum;
import com.feng.exception.SystemException;
import com.feng.service.AdminLoginService;
import com.feng.service.MenuService;
import com.feng.service.RoleService;
import com.feng.utils.BeanCopyUtil;
import com.feng.utils.RedisCache;
import com.feng.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class AdminLoginController {

    @Autowired
    private AdminLoginService adminLoginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisCache redisCache;

    @PostMapping("/adminLogin")
    public ResponseResult login(@RequestBody LoginUserDto loginUserDto){
        if(!StringUtils.hasText(loginUserDto.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if (!StringUtils.hasText(loginUserDto.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        User user = BeanCopyUtil.articleVo(loginUserDto, User.class);
        return adminLoginService.login(user);
    }

    @GetMapping("/getInfo")
    public ResponseResult getInfo(){
        LoginUser loginUser = SecurityUtils.getLoginUser();

        //查询用户权限
        List<String> perms = menuService.selectMenuByUserId(loginUser.getUser().getId());

        //查询用户角色
        List<String> roleKey = roleService.selectRoleByUserId(loginUser.getUser().getId());

        //封装用户信息
        User user = loginUser.getUser();
        UserInfoVo userInfoVo = BeanCopyUtil.articleVo(user, UserInfoVo.class);

        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms, roleKey, userInfoVo);
        //返回

        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult getRouters(){
        Long userId = SecurityUtils.getUserId();
        List<MenuVo> menuVos = menuService.selectRouterMenuTreeByUserId(userId);
        return ResponseResult.okResult(new RoutersVo(menuVos));
    }

    @PostMapping("/logout")
    public ResponseResult logout(){
        Long userId = SecurityUtils.getUserId();
        redisCache.deleteObject("AdminLogin:" + userId);
        return ResponseResult.okResult();
    }
}
